#!/bin/bash

# 用户体验优化测试脚本
echo "=== 高考志愿推荐系统用户体验测试 ==="
echo "测试时间: $(date)"
echo ""

# 测试参数
BASE_URL="http://localhost:8080"
RECOMMEND_ENDPOINT="/admin-api/system/college-recommendation/recommend"
FAST_ENDPOINT="/admin-api/system/college-recommendation/recommend-fast"

# 测试数据
TEST_DATA='{
  "province": "辽宁",
  "score": 550,
  "ranks": 25000,
  "year": 2024,
  "classify": "物理类",
  "subjects": "物理,化学",
  "batch": "本科批",
  "pageNum": 1,
  "pageSize": 50
}'

LARGE_DATA='{
  "province": "辽宁", 
  "score": 500,
  "ranks": 40000,
  "year": 2024,
  "classify": "物理类",
  "subjects": "物理",
  "batch": "本科批",
  "pageNum": 1,
  "pageSize": 200
}'

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 测试结果统计
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# 测试函数
run_test() {
    local test_name="$1"
    local endpoint="$2"
    local data="$3"
    local expected_time="$4"
    
    echo -e "${BLUE}测试: $test_name${NC}"
    echo "端点: $endpoint"
    echo "预期响应时间: < ${expected_time}秒"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    # 执行请求
    START_TIME=$(date +%s%3N)
    RESPONSE=$(curl -s -w "\n%{http_code}\n%{time_total}" \
        -H "Content-Type: application/json" \
        -X POST "${BASE_URL}${endpoint}" \
        -d "$data" 2>/dev/null)
    
    # 解析响应
    HTTP_CODE=$(echo "$RESPONSE" | tail -n2 | head -n1)
    TIME_TOTAL=$(echo "$RESPONSE" | tail -n1)
    RESPONSE_BODY=$(echo "$RESPONSE" | head -n -2)
    
    # 转换时间为毫秒
    TIME_MS=$(echo "$TIME_TOTAL * 1000" | bc -l | cut -d. -f1)
    
    echo "HTTP状态码: $HTTP_CODE"
    echo "响应时间: ${TIME_MS}ms (${TIME_TOTAL}s)"
    
    # 检查结果
    if [ "$HTTP_CODE" = "200" ]; then
        # 检查响应时间
        if (( $(echo "$TIME_TOTAL < $expected_time" | bc -l) )); then
            echo -e "${GREEN}✅ 测试通过${NC}"
            PASSED_TESTS=$((PASSED_TESTS + 1))
            
            # 检查响应内容
            RESULT_COUNT=$(echo "$RESPONSE_BODY" | grep -o '"total":[0-9]*' | grep -o '[0-9]*' 2>/dev/null || echo "0")
            echo "推荐结果数量: $RESULT_COUNT"
            
        else
            echo -e "${YELLOW}⚠️  响应时间超出预期${NC}"
            FAILED_TESTS=$((FAILED_TESTS + 1))
        fi
    else
        echo -e "${RED}❌ 测试失败 - HTTP $HTTP_CODE${NC}"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        echo "错误响应: $(echo "$RESPONSE_BODY" | head -c 200)"
    fi
    
    echo ""
}

# 测试1: 快速推荐接口
echo "=== 测试1: 快速推荐接口 ==="
run_test "快速推荐 - 小数据量" "$FAST_ENDPOINT" "$TEST_DATA" "5"

# 测试2: 异步推荐接口 - 小数据量
echo "=== 测试2: 异步推荐接口 - 小数据量 ==="
run_test "异步推荐 - 小数据量" "$RECOMMEND_ENDPOINT" "$TEST_DATA" "15"

# 测试3: 异步推荐接口 - 大数据量
echo "=== 测试3: 异步推荐接口 - 大数据量 ==="
run_test "异步推荐 - 大数据量" "$RECOMMEND_ENDPOINT" "$LARGE_DATA" "30"

# 测试4: 并发性能测试
echo "=== 测试4: 并发性能测试 ==="
echo "启动3个并发快速推荐请求..."

CONCURRENT_PIDS=()
CONCURRENT_TIMES=()

for i in {1..3}; do
    {
        START_TIME=$(date +%s%3N)
        RESPONSE=$(curl -s -w "%{http_code}" \
            -H "Content-Type: application/json" \
            -X POST "${BASE_URL}${FAST_ENDPOINT}" \
            -d "$TEST_DATA" 2>/dev/null)
        END_TIME=$(date +%s%3N)
        
        DURATION=$((END_TIME - START_TIME))
        HTTP_CODE=$(echo "$RESPONSE" | tail -c 4)
        
        echo "并发请求 $i: HTTP $HTTP_CODE, 耗时: ${DURATION}ms"
        echo "$DURATION" > "/tmp/concurrent_test_$i.tmp"
    } &
    CONCURRENT_PIDS+=($!)
done

# 等待所有并发请求完成
for pid in "${CONCURRENT_PIDS[@]}"; do
    wait $pid
done

# 计算并发测试结果
echo "并发测试结果:"
TOTAL_CONCURRENT_TIME=0
for i in {1..3}; do
    if [ -f "/tmp/concurrent_test_$i.tmp" ]; then
        TIME=$(cat "/tmp/concurrent_test_$i.tmp")
        TOTAL_CONCURRENT_TIME=$((TOTAL_CONCURRENT_TIME + TIME))
        rm "/tmp/concurrent_test_$i.tmp"
    fi
done

AVG_CONCURRENT_TIME=$((TOTAL_CONCURRENT_TIME / 3))
echo "平均并发响应时间: ${AVG_CONCURRENT_TIME}ms"

if [ $AVG_CONCURRENT_TIME -lt 8000 ]; then
    echo -e "${GREEN}✅ 并发性能测试通过${NC}"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo -e "${YELLOW}⚠️  并发性能需要优化${NC}"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi
TOTAL_TESTS=$((TOTAL_TESTS + 1))
echo ""

# 测试5: 超时处理测试
echo "=== 测试5: 超时处理测试 ==="
echo "测试超大数据量请求的超时处理..."

TIMEOUT_DATA='{
  "province": "辽宁",
  "score": 400,
  "ranks": 80000,
  "year": 2024,
  "classify": "物理类",
  "subjects": "",
  "batch": "本科批",
  "pageNum": 1,
  "pageSize": 1000
}'

START_TIME=$(date +%s)
timeout 35s curl -s -w "\n%{http_code}" \
    -H "Content-Type: application/json" \
    -X POST "${BASE_URL}${RECOMMEND_ENDPOINT}" \
    -d "$TIMEOUT_DATA" > timeout_test.tmp 2>&1

CURL_EXIT_CODE=$?
END_TIME=$(date +%s)
TIMEOUT_DURATION=$((END_TIME - START_TIME))

echo "超时测试耗时: ${TIMEOUT_DURATION}秒"

if [ $CURL_EXIT_CODE -eq 124 ]; then
    echo -e "${GREEN}✅ 超时处理正常 - 请求在35秒内被终止${NC}"
    PASSED_TESTS=$((PASSED_TESTS + 1))
elif [ $CURL_EXIT_CODE -eq 0 ]; then
    HTTP_CODE=$(tail -n1 timeout_test.tmp)
    if [ "$HTTP_CODE" = "408" ]; then
        echo -e "${GREEN}✅ 服务端超时处理正常 - 返回408状态码${NC}"
        PASSED_TESTS=$((PASSED_TESTS + 1))
    else
        echo -e "${YELLOW}⚠️  请求完成但耗时较长: ${TIMEOUT_DURATION}秒${NC}"
        FAILED_TESTS=$((FAILED_TESTS + 1))
    fi
else
    echo -e "${RED}❌ 超时测试异常${NC}"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi

TOTAL_TESTS=$((TOTAL_TESTS + 1))
rm -f timeout_test.tmp
echo ""

# 测试6: 缓存效果测试
echo "=== 测试6: 缓存效果测试 ==="
echo "测试相同请求的缓存效果..."

# 第一次请求
echo "第一次请求（无缓存）:"
START_TIME=$(date +%s%3N)
RESPONSE1=$(curl -s -w "%{time_total}" \
    -H "Content-Type: application/json" \
    -X POST "${BASE_URL}${FAST_ENDPOINT}" \
    -d "$TEST_DATA" 2>/dev/null)
TIME1=$(echo "$RESPONSE1" | tail -n1)
TIME1_MS=$(echo "$TIME1 * 1000" | bc -l | cut -d. -f1)
echo "第一次响应时间: ${TIME1_MS}ms"

# 等待1秒
sleep 1

# 第二次请求（可能命中缓存）
echo "第二次请求（可能命中缓存）:"
START_TIME=$(date +%s%3N)
RESPONSE2=$(curl -s -w "%{time_total}" \
    -H "Content-Type: application/json" \
    -X POST "${BASE_URL}${FAST_ENDPOINT}" \
    -d "$TEST_DATA" 2>/dev/null)
TIME2=$(echo "$RESPONSE2" | tail -n1)
TIME2_MS=$(echo "$TIME2 * 1000" | bc -l | cut -d. -f1)
echo "第二次响应时间: ${TIME2_MS}ms"

# 计算缓存效果
if [ $TIME2_MS -lt $TIME1_MS ]; then
    IMPROVEMENT=$((TIME1_MS - TIME2_MS))
    IMPROVEMENT_PERCENT=$(echo "scale=1; $IMPROVEMENT * 100 / $TIME1_MS" | bc -l)
    echo -e "${GREEN}✅ 缓存效果明显 - 提升${IMPROVEMENT}ms (${IMPROVEMENT_PERCENT}%)${NC}"
    PASSED_TESTS=$((PASSED_TESTS + 1))
else
    echo -e "${YELLOW}⚠️  缓存效果不明显${NC}"
    FAILED_TESTS=$((FAILED_TESTS + 1))
fi

TOTAL_TESTS=$((TOTAL_TESTS + 1))
echo ""

# 测试总结
echo "=== 测试总结 ==="
echo "总测试数: $TOTAL_TESTS"
echo -e "通过测试: ${GREEN}$PASSED_TESTS${NC}"
echo -e "失败测试: ${RED}$FAILED_TESTS${NC}"

SUCCESS_RATE=$(echo "scale=1; $PASSED_TESTS * 100 / $TOTAL_TESTS" | bc -l)
echo "成功率: ${SUCCESS_RATE}%"

echo ""
echo "=== 用户体验评估 ==="

if [ $PASSED_TESTS -ge $((TOTAL_TESTS * 80 / 100)) ]; then
    echo -e "${GREEN}🎉 用户体验优化效果良好！${NC}"
    echo "建议:"
    echo "- 快速推荐功能可以投入使用"
    echo "- 异步推荐提供了良好的用户体验"
    echo "- 系统具备良好的并发处理能力"
elif [ $PASSED_TESTS -ge $((TOTAL_TESTS * 60 / 100)) ]; then
    echo -e "${YELLOW}⚠️  用户体验有待改进${NC}"
    echo "建议:"
    echo "- 进一步优化响应时间"
    echo "- 检查缓存机制是否正常工作"
    echo "- 考虑增加更多的性能优化措施"
else
    echo -e "${RED}❌ 用户体验需要重大改进${NC}"
    echo "建议:"
    echo "- 检查系统配置和JVM参数"
    echo "- 优化数据库查询性能"
    echo "- 考虑使用更强大的硬件资源"
fi

echo ""
echo "=== 性能基准 ==="
echo "快速推荐目标: < 5秒"
echo "异步推荐目标: < 30秒"
echo "并发处理目标: < 8秒平均响应时间"
echo "缓存效果目标: 第二次请求提升 > 20%"
echo ""
echo "测试完成时间: $(date)"
